import java.util.PriorityQueue;

/**
 * @author hewei
 * @version 1.0
 * @description: 1705. 吃苹果的最大数目
 * @date 2022/11/8 14:02
 */

public class EatenApples {

    public static void main(String[] args) {
        int[] nums1 = {3,0,0,0,0,2};
        int[] nums2 = {3,0,0,0,0,2};
        System.out.println(new EatenApples().eatenApples(nums1, nums2));
    }

    public int eatenApples(int[] apples, int[] days) {
        PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> {
            if (a + days[a] != b + days[b]) return a + days[a] - days[b] - b;
            return apples[a] - apples[b];
        });
        int cur = 0, n = days.length, ans = 0;
        heap.add(0);
        while (!heap.isEmpty()) {
            while (!heap.isEmpty() && (days[heap.peek()] + heap.peek() <= cur || apples[heap.peek()] == 0)) heap.poll();
            if (!heap.isEmpty()) {
                Integer poll = heap.peek();
                apples[poll]--;
                ++ans;
            }
            ++cur;
            if (cur < n) heap.offer(cur);
        }
        return ans;
    }
}
